package com.weichen.studentgameexchange.game.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.weichen.studentgameexchange.common.common.Result;
import com.weichen.studentgameexchange.common.common.StrIsNumOrChinese;
import com.weichen.studentgameexchange.common.exception.ServiceException;
import com.weichen.studentgameexchange.game.dao.GenreMapper;
import com.weichen.studentgameexchange.game.entity.*;
import com.weichen.studentgameexchange.game.entity.vo.GenreVo;
import com.weichen.studentgameexchange.game.entity.vo.UserGenreVo;
import com.weichen.studentgameexchange.game.service.IGenreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 惟尘
 * @since 2025-02-01
 */
@Service
public class GenreServiceImpl extends ServiceImpl<GenreMapper, Genre> implements IGenreService {

    @Autowired
    GenreMapper genreMapper;

    private double gradeCount = 0.0;

    /**
     * 新增游戏类型
     *
     * @param genre
     */
    @Override
    public Result adminAdd(Genre genre) {
        Genre one = Db.lambdaQuery(Genre.class)
                .eq(genre.getGenreName() != null, Genre::getGenreName, genre.getGenreName())
                .one();
        if (one != null)
            return Result.error("游戏类型已存在！");
        genreMapper.insert(genre);
        return Result.success();
    }

    /**
     * 分页查询
     *
     * @param keyword
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Genre> adminPage(String keyword, Integer page, Integer size) {
        Page<Genre> genrePage = new Page<>(page, size);
        LambdaQueryWrapper<Genre> genreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        genreLambdaQueryWrapper
                .orderByDesc(Genre::getGenreId)
                .like(keyword != null, Genre::getGenreName, keyword);
        return genreMapper.selectPage(genrePage, genreLambdaQueryWrapper);
    }

    /**
     * 修改游戏类型
     *
     * @param genrevo
     * @return
     */
    @Override
    public Result adminUpdate(GenreVo genrevo) {
        Long genreId = genrevo.getGenreId();
        if (genreId == null)
            throw new ServiceException("游戏类型Id不能为空！");
        List<String> gameNames = genrevo.getGameNames();
        Genre genre = BeanUtil.copyProperties(genrevo, Genre.class);
        genreMapper.insertOrUpdate(genre);
        if (gameNames.size() > 0) {
            List<Long> gameIds = Db.lambdaQuery(Game.class)
                    .in(Game::getGameName, gameNames)
                    .list()
                    .stream()
                    .map(Game::getGameId)
                    .toList();
            Db.lambdaUpdate(GameGenre.class)
                    .eq(GameGenre::getGenreId, genreId)
                    .remove();
            gameIds.forEach(gameId -> {
                GameGenre gameGenre = new GameGenre();
                gameGenre.setGenreId(genreId);
                gameGenre.setGameId(gameId);
                Db.save(gameGenre);
            });
        }
        return Result.success();
    }

    /**
     * 删除单个游戏类型
     *
     * @param genreId
     */
    @Override
    public void adminDeleteOne(Long genreId) {
        if (genreId == null)
            throw new ServiceException("游戏类型Id不能为空!");
        Genre one = Db.lambdaQuery(Genre.class)
                .eq(Genre::getGenreId, genreId)
                .one();
        if (one == null)
            throw new ServiceException("游戏类型不存在！");
        List<Long> gameIds = Db.lambdaQuery(GameGenre.class)
                .eq(GameGenre::getGenreId, genreId)
                .list()
                .stream()
                .map(GameGenre::getGameId)
                .toList();
        if (gameIds.size() != 0) {
            gameIds.forEach(gameId -> {
                Db.lambdaUpdate(GameGenre.class)
                        .eq(GameGenre::getGameId, gameId)
                        .eq(GameGenre::getGenreId, genreId)
                        .remove();
            });
        }
        Db.lambdaUpdate(Genre.class)
                .eq(Genre::getGenreId, genreId)
                .remove();
    }

    /**
     * 修改界面查看游戏名称
     *
     * @param genreId
     * @return
     */
    @Override
    public Result adminSelectOneUpdate(Long genreId) {
        Genre genre = genreMapper.selectById(genreId);
        GenreVo genreVo = BeanUtil.copyProperties(genre, GenreVo.class);
        List<GameGenre> gameGenres = Db.lambdaQuery(GameGenre.class)
                .eq(GameGenre::getGenreId, genreId)
                .list();
        if (gameGenres.size() == 0) {
            genreVo.setGameNames(null);
            return Result.success(genreVo);
        }
        List<Long> gameIds = gameGenres
                .stream()
                .map(GameGenre::getGameId)
                .toList();
        if (gameIds.size() == 0) {
            genreVo.setGenreName("");
        }
        List<String> gameNames = Db.lambdaQuery(Game.class)
                .in(Game::getGameId, gameIds)
                .list()
                .stream()
                .map(Game::getGameName)
                .toList();
        genreVo.setGameNames(gameNames);
        return Result.success(genreVo);
    }

    @Override
    public Result userPage(Long gnreId, Integer page, Integer size) {
        Page<Genre> genrePage = new Page<>(page,size);
        LambdaQueryWrapper<Genre> genreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        genreLambdaQueryWrapper.orderByDesc(Genre::getGenreId).eq(Genre::getGenreId,gnreId);
        Genre selectOne = genreMapper.selectOne(genreLambdaQueryWrapper);
        Page<Genre> selectPage = genreMapper.selectPage(genrePage, genreLambdaQueryWrapper);
        List<Long> gameIds = Db.lambdaQuery(GameGenre.class)
                .eq(GameGenre::getGenreId, gnreId)
                .list()
                .stream()
                .map(GameGenre::getGameId)
                .toList();
        List<Game> games = Db.lambdaQuery(Game.class)
                .in(Game::getGameId, gameIds)
                .list();
        List<UserGenreVo> vos = new ArrayList<>();
        games.forEach(game -> {
            gradeCount = 0.0;
            UserGenreVo vo = BeanUtil.copyProperties(game, UserGenreVo.class);
            int count = Db.lambdaQuery(UserGameCollection.class)
                    .eq(UserGameCollection::getGameId, game.getGameId())
                    .list()
                    .size();
            vo.setCollectionCount(count);
            List<UserGameGrade> list = Db.lambdaQuery(UserGameGrade.class)
                    .eq(UserGameGrade::getGameId, game.getGameId())
                    .list();
            if (list.size()>0){
                List<BigDecimal> bigDecimals = list.stream().map(UserGameGrade::getGradeScore).toList();
                bigDecimals.forEach(bigDecimal -> {
                    double v = bigDecimal.doubleValue();
                    gradeCount = gradeCount + v;
                });
                gradeCount = gradeCount/(list.size());
            }
            vo.setGradeCount(gradeCount);
            vo.setGenreName(selectOne.getGenreName());
            vos.add(vo);
        });
        Page<UserGenreVo> userGenreVoPage  =new Page<>();
        userGenreVoPage.setCurrent(selectPage.getCurrent());
        userGenreVoPage.setSize(selectPage.getSize());
        userGenreVoPage.setTotal(selectPage.getTotal());
        userGenreVoPage.setRecords(vos);
        return Result.success(userGenreVoPage);
    }
}
